<template>
  <el-card shadow="never" class="aui-card--fill">
    <div class="mod-police__order}">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.serviceItem" placeholder="请输入服务项目" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.orderCode" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.creatorName" placeholder="请输入签约人" clearable></el-input>
        </el-form-item>
      </el-form>
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-select v-model="dataForm.customerId" filterable clearable placeholder="请选择客户">
            <el-option v-for="item in customerInfoList" :key="item.id" :label="item.companyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="dataForm.orderStatus" clearable placeholder="请选择订单状态">
            <el-option v-for="item in orderStatusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="dataForm.orderContractStatus" clearable placeholder="请选择合同状态">
            <el-option v-for="item in orderContractStatusList" :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-button @click="getDataList()">{{ $t("query") }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="exportHandle()">{{
            $t("export")
            }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addOrUpdateHandle()">{{
            $t("add")
            }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="flag" type="danger" @click="deleteHandle()">{{
            $t("deleteBatch")
            }}</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle"
        style="width: 100%">
        <el-table-column v-if="flag" type="selection" header-align="center" align="center" width="50"></el-table-column>
        <el-table-column label="公司名称" header-align="center" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="showCompany(scope.row.customerInfoDto)">{{
              scope.row.customerInfoDto.companyName }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="serviceItem" label="服务项目" header-align="center" align="center"></el-table-column>
        <el-table-column prop="orderCode" label="订单编号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="costAmount" label="订单成本" header-align="center" align="center"></el-table-column>
        <el-table-column prop="totalAmount" label="订单总金额" header-align="center" align="center"></el-table-column>
        <el-table-column prop="totalPayAmount" label="已支付金额" header-align="center" align="center"></el-table-column>
        <el-table-column prop="totalUnPayAmount" label="未支付金额" header-align="center" align="center"></el-table-column>
        <el-table-column prop="introducer" label="介绍人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.orderStatus === 0" size="small" type="danger">未完结</el-tag>
            <el-tag v-if="scope.row.orderStatus === 1" size="small" type="success">已完结</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="orderContractStatus" label="合同状态" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.orderContractStatus === 0" type="text" size="small" @click="signContract(scope.row.id)">补签合同</el-button>
            <el-tag v-if="scope.row.orderContractStatus === 1" size="small" type="success">已签合同</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报价图片" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.amountImagePathSize === 0" size="small" type="danger">暂无图片</el-tag>
            <el-image v-else style="width: 20px; height: 20px" :src="url"
              :preview-src-list="scope.row.amountImageUrlList"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="合同图片" header-align="center" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.imageDataSize === 0" size="small" type="danger">暂无图片</el-tag>
            <el-image v-else style="width: 20px; height: 20px" :src="url"
              :preview-src-list="scope.row.imageDataUrlList"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="合同下载" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="download(scope.row)">合同下载</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="签约人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="createDate" label="接单时间" header-align="center" align="center"></el-table-column>
        <el-table-column prop="finishDate" label="完结时间" header-align="center" align="center"></el-table-column>
        <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="flag" type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ $t("update")
              }}</el-button>
            <el-button v-if="scope.row.orderStatus === 0" type="text" size="small"
              @click="addOrUpdateOrderPayment(scope.row.id)">收款</el-button>
            <el-button v-if="scope.row.orderStatus === 0" type="text" size="small"
              @click="finishOrder(scope.row)">完结</el-button>
            <el-button type="text" size="small" @click="getOrderpaymentListByOrderId(scope.row.id)"
              style="margin-left: 16px">收款详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      <sign-contract v-if="signContractVisible" ref="signContract" @refreshDataList="getDataList"></sign-contract>
      <add-or-update-order-payment v-if="addOrUpdateOrderPaymentVisible" ref="addOrUpdateOrderPayment"
        @refreshDataList="getDataList"></add-or-update-order-payment>
    </div>
    <el-dialog title="公司详细信息" :visible.sync="dialogVisible" width="30%">
      <p>联系人: {{ showCompanyData.contactPerson }}</p>
      <p>联系电话: {{ showCompanyData.contactPhone }}</p>
      <p>
        客户类型: {{ showCompanyData.customerType == 0 ? "新客户" : "老客户" }}
      </p>
    </el-dialog>
    <el-drawer title="收款详情" :visible.sync="drawer" :with-header="true" size="30%">
      <el-timeline style="margin-top: 30px">
        <el-empty v-if="!orderPaymentInfoList.length" description="暂无数据"></el-empty>
        <el-timeline-item v-else v-for="(orderPaymentInfo, index) in orderPaymentInfoList" :key="index"
          :timestamp="orderPaymentInfo.createDate">
          <StampBadge 
            v-if="orderPaymentInfo.isExamine == 0"
            style="position: absolute; top: 0; right: 50px"
            size="middle"
            color="info"
            content="暂未审核"
            :rotate="45"
          />
          <StampBadge 
            v-if="orderPaymentInfo.isExamine == 1"
            style="position: absolute; top: 0; right: 50px"
            size="middle"
            color="success"
            content="审核成功"
            :rotate="45"
          />
          <StampBadge 
            v-if="orderPaymentInfo.isExamine == 2"
            style="position: absolute; top: 0; right: 50px"
            size="middle"
            color="error"
            content="审核失败"
            :rotate="45"
          />
          <p>
            支付金额:
            <i style="font-size: 25px">{{ orderPaymentInfo.payAmount }}</i>
          </p>
          <p>付款时间: {{ orderPaymentInfo.payDate }}</p>
          <p>备注信息: {{ orderPaymentInfo.remark }}</p>
          <p>
            支付方式:
            <el-tag v-if="orderPaymentInfo.paymentMethod === 0" size="small" type="warning">公账</el-tag>
            <el-tag v-if="orderPaymentInfo.paymentMethod === 1" size="small" type="success">个人</el-tag>
          </p>
          <p>
            <el-switch style="display: block; margin-bottom: 2px" v-model="orderPaymentInfo.isInvoice" :active-value="1"
              :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" active-text="已开票" inactive-text="未开票"
              @change="invoiceChange(orderPaymentInfo)">
            </el-switch>
          </p>
          <p>
            是否回款:
            <el-tag v-if="orderPaymentInfo.isReceived === 0" size="small" type="danger">未回款</el-tag>
            <el-tag v-if="orderPaymentInfo.isReceived === 1" size="small" type="success">已回款</el-tag>
          </p>
          <p>回款审核员: {{ orderPaymentInfo.processReceivedUserName }}</p>
          <p>审核员备注信息: {{ orderPaymentInfo.processRemark }}</p>
          <div v-if="
            orderPaymentInfo.imagePath !== '' &&
            orderPaymentInfo.imagePath !== null
          ">
            <p>点击下方图标查看支付截图：</p>
            <el-image style="width: 20px; height: 20px" :src="url"
              :preview-src-list="orderPaymentInfo.imageDataUrlList"></el-image>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>
  </el-card>
</template>

<script>
import JSZip from "jszip";
import { saveAs } from "file-saver";
import mixinViewModule from "@/mixins/view-module";
import AddOrUpdate from "./order-add-or-update";
import SignContract from "./sign-contract";
import StampBadge from "./stamp-badge";
import addOrUpdateOrderPayment from "./orderpayment-add-or-update";
export default {
  mixins: [mixinViewModule],
  data() {
    return {
      mixinViewModuleOptions: {
        getDataListURL: "/order/order/page",
        getDataListIsPage: true,
        exportURL: "/order/order/export",
        deleteURL: "/order/order",
        deleteIsBatch: true,
      },
      dataForm: {
        serviceItem: "",
        orderCode: "",
        customerId: "",
        creatorName: ""
      },
      orderStatusList: [
        {
          label: "未完结",
          value: 0,
        },
        {
          label: "已完结",
          value: 1,
        },
      ],
      orderContractStatusList: [
        {
          label: "未签合同",
          value: 0,
        },
        {
          label: "已签合同",
          value: 1,
        },
      ],
      customerInfoList: [],
      dialogVisible: false,
      showCompanyData: {},
      addOrUpdateOrderPaymentVisible: false,
      signContractVisible: false,
      drawer: false,
      orderPaymentInfoList: [],
      url: "./picture.png",
      flag: false,
    };
  },
  components: {
    AddOrUpdate,
    addOrUpdateOrderPayment,
    SignContract,
    StampBadge
  },
  created() {
    this.getAllCustomers();
    this.isOfficeRole();
  },
  methods: {
    // 补签合同
    signContract(id) {
      this.signContractVisible = true;
      this.$nextTick(() => {
        this.$refs.signContract.dataForm.id = id;
        this.$refs.signContract.init();
      });
    },
    // 收款
    addOrUpdateOrderPayment(id) {
      this.addOrUpdateOrderPaymentVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdateOrderPayment.dataForm.orderId = id;
        this.$refs.addOrUpdateOrderPayment.init();
      });
    },
    // 根据订单ID查询付款记录
    getOrderpaymentListByOrderId(orderId) {
      this.drawer = true;
      this.$http
        .get("/order/orderpayment/listByOrderId/" + orderId)
        .then(({ data }) => {
          this.orderPaymentInfoList = data.data;
        });
    },
    // 开发票提交
    invoiceChange(row) {
      this.$http
        .put("/order/orderpayment", {
          id: row.id,
          orderId: row.orderId,
          isInvoice: row.isInvoice,
        })
        .then(({ data: res }) => {
          if (res.code == 0) {
            this.$message({
              message: "发票提交成功",
              type: "success",
            });
          } else {
            this.$message.error("发票提交失败");
          }
        });
    },
    // 获取所有的客户信息
    getAllCustomers() {
      this.$http.get("/customer/customerinfo/list").then(({ data }) => {
        this.customerInfoList = data.data;
      });
    },
    // 是否具有办公室角色
    isOfficeRole() {
      this.$http.get("/sys/role/isOfficeRole").then(({ data }) => {
        this.flag = data.data;
      });
    },
    // 展示公司信息
    showCompany(item) {
      console.log(item);
      this.dialogVisible = true;
      this.showCompanyData = item;
    },
    // 订单完结提交
    finishOrder(item) {
      this.$confirm("订单" + item.orderCode + "是否完结？", "提示", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning",
      }).then(() => {
        this.$http
          .post("/order/order/finishOrder", {
            id: item.id
          })
          .then(({ data: res }) => {
            if (res.code == 0) {
              this.$message({
                message: "该订单已完结!",
                type: "success",
              });
              this.getDataList();
            } else {
              this.$message.error("订单提交失败!");
            }
          });
      });
    },
    // 下载的具体方法
    async download(row) {
      const data = row; // 假设 row 包含 imageDataList 和 fileDataList
      // 获取文件列表
      const imageDataList = data.imageDataList || [];
      const fileDataList = data.fileDataList || [];
      const zip = new JSZip();
      const files = [...imageDataList, ...fileDataList];
      const downloadPromises = files.map(async (file) => {
        try {
          const response = await fetch(file.url);
          if (!response.ok) {
            throw new Error(
              `Failed to fetch ${file.url}: ${response.statusText}`
            );
          }
          const blob = await response.blob();
          const fileName = file.name.split("/").pop(); // 提取文件名
          zip.file(fileName, blob);
        } catch (error) {
          console.error(`Error downloading ${file.name}:`, error);
        }
      });
      // 等待所有文件下载完成
      await Promise.all(downloadPromises);
      // 生成 ZIP 文件并下载
      zip
        .generateAsync({ type: "blob" })
        .then((content) => {
          saveAs(content, "合同文件.zip");
        })
        .catch((error) => {
          console.error("Error generating ZIP file:", error);
        });
    },
  },
};
</script>
